//
//  SXDataBaseManager.m
//  ShiXun
//
//  Created by lanou on 15/10/24.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXDataBaseManager.h"

@implementation SXDataBaseManager

// 数据库操作
+ (void)DBManage:(NSData *)data dataName:(NSString *)dataName manageType:(dataBaseManageType)type getDataFromDict:(getDataFromDict)getDataBlock
{
    NSString *docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dbpath = [docsdir stringByAppendingPathComponent:@"user.sqlite"];
    FMDatabase *db = [FMDatabase databaseWithPath:dbpath];
    
    if([db open])
    {
        NSString *sql = [NSString stringWithFormat:@"create table if not exists usrTable (dataName text primary key, jsonData blob)"];
        BOOL rs = [db executeUpdate:sql];
        if(!rs)
        {
            NSLog(@"error create table!");
        }else
        {
            //            NSLog(@"successed create table!");
            if(type == dataBaseManageTypeStoreData)
            {
                [self dataStoreIntoDB:db data:data dataName:dataName];
            }else
            {
                [self dataQueryFromDB:db getDataFromDict:getDataBlock dataName:dataName];
            }
        }
    }
}

// 数据库存储数据
+ (void)dataStoreIntoDB:(FMDatabase *)db data:(NSData *)data dataName:(NSString *)dataName
{
    NSString *deleteSql = [NSString stringWithFormat:@"delete from usrTable where dataName = ?"];
    BOOL rs = [db executeUpdate:deleteSql, dataName];
    
    if(!rs)
    {
        NSLog(@"error delete data");
    }else
    {
        //        NSLog(@"successed delete data");
    }
    
    NSString *sql = [NSString stringWithFormat:@"insert into usrTable (dataName, jsonData) values (?, ?)"];
    BOOL res = [db executeUpdate:sql, dataName, data];
    if(!res)
    {
        NSLog(@"error insert data");
    }else
    {
//        NSLog(@"successed insert data");
    }
    [db close];
}

// 数据库查询数据
+ (void)dataQueryFromDB:(FMDatabase *)db getDataFromDict:(getDataFromDict)getDataBlock dataName:(NSString *)dataName
{
    NSString *sql = @"select jsonData from usrTable where dataName = ?";
    FMResultSet * rs = [db executeQuery:sql, dataName];
    while ([rs next])
    {
        NSData *jsonData = [rs dataForColumnIndex:0];
        getDataBlock(jsonData);
    }
    [db close];
}


@end
